package com.example.app.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.app.common.ErrorCode;
import com.example.app.common.Role;
import com.example.app.common.UserStatus;
import com.example.app.entity.User;
import com.example.app.entity.dto.DeleteRequest;
import com.example.app.entity.dto.LoginDTO;
import com.example.app.entity.dto.RegisterDTO;
import com.example.app.entity.dto.ResetPasswordDTO;
import com.example.app.entity.dto.UpdateUserDTO;
import com.example.app.entity.dto.UserManageDTO;
import com.example.app.entity.dto.UserQueryRequest;
import com.example.app.entity.dto.ChangePasswordDTO;
import com.example.app.entity.vo.UserPageVO;
import com.example.app.entity.vo.UserVO;
import com.example.app.service.UserService;

import com.example.app.mapper.UserMapper;
import com.example.app.utils.JwtUtils;
import com.example.app.utils.RedisUtils;
import com.example.app.utils.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author 15790
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-04-01 20:47:22
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Value(value = "${encrypt.salt}")
    private static String salt;

    /**
     * redis token前缀
     */
    private final String TOKEN_PRE = "TOKEN_";

    /**
     * redis 用户id前缀
     */
    private final String USER_ID = "USER_ID_";

    @Value(value = "${spring.redis.expire}")
    private long redisExpire;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public Boolean register(RegisterDTO registerDTO) {
        //校验注册参数
        String username = registerDTO.getUsername();
        String password = registerDTO.getPassword();
        String repeatPassword = registerDTO.getRepeatPassword();
        String email = registerDTO.getEmail();
        String phone = registerDTO.getPhone();
        ThrowUtils.throwIf(StrUtil.hasBlank(username, password, repeatPassword, email), ErrorCode.PARAMS_ERROR, "必填项不可为空");
        ThrowUtils.throwIf(!password.equals(repeatPassword), ErrorCode.PARAMS_ERROR, "两次输入密码不一致");
        ThrowUtils.throwIf(!Validator.isEmail(email), ErrorCode.PARAMS_ERROR, "邮箱格式不正确");
        ThrowUtils.throwIf(!StrUtil.isEmpty(phone) && !Validator.isMobile(phone), ErrorCode.PARAMS_ERROR, "手机号格式不正确");
        //用户名是否存在
        QueryWrapper<User> userNameQuery = new QueryWrapper<>();
        userNameQuery.eq("username", username);
        ThrowUtils.throwIf(this.exists(userNameQuery), ErrorCode.PARAMS_ERROR, "用户名已存在");
        //密码加密
        String encryptPassword = MD5.create().digestHex(password, salt);
        //设置加密密码
        registerDTO.setPassword(encryptPassword);
        //新建用户对象并赋值
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        //保存用户
        return this.save(user);
    }

    @Override
    public UserVO login(LoginDTO loginDTO, HttpServletRequest request) {
        //判断是否已经登录过
        String tokenLogin = request.getHeader("Auth");
        ThrowUtils.throwIf(jwtUtils.checkToken(tokenLogin) && redisUtils.hasKey(TOKEN_PRE + tokenLogin), ErrorCode.PARAMS_ERROR, "已登录");

        //开启登录流程
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        ThrowUtils.throwIf(StrUtil.hasEmpty(username, password), ErrorCode.PARAMS_ERROR, "用户名或密码为空");

        //判断用户名密码
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);

        //密码加密
        String encryptPassword = MD5.create().digestHex(password, salt);
        userQueryWrapper.eq("password", encryptPassword);
        User user = this.getOne(userQueryWrapper);
        ThrowUtils.throwIf(user == null, ErrorCode.PARAMS_ERROR, "用户名或密码错误");
        ThrowUtils.throwIf(user.getStatus() == UserStatus.BAN.getStatus(), ErrorCode.FORBIDDEN_ERROR, "您已被封禁");

        //生成token
        String token = jwtUtils.createToken(user.getId());
        redisUtils.set(TOKEN_PRE + token, JSON.toJSONString(user), redisExpire);
        redisUtils.set(USER_ID + user.getId(), TOKEN_PRE + token, redisExpire);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setToken(token);
        return userVO;
    }

    @Override
    public UserVO getLoginUserInfo(HttpServletRequest request) {
        //取出Token
        String token = request.getHeader("Auth");
        //校验Token
        ThrowUtils.throwIf(!jwtUtils.checkToken(token), ErrorCode.NOT_LOGIN_ERROR);
        //从Redis取出用户信息
        String userInfoJson = redisUtils.getString(TOKEN_PRE + token);
        ThrowUtils.throwIf(StrUtil.isEmpty(userInfoJson), ErrorCode.NOT_LOGIN_ERROR, "登录过期");
        User user = JSON.parseObject(userInfoJson, User.class);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public void loginOut(DeleteRequest deleteRequest, HttpServletRequest request) {
        Long id = deleteRequest.getId();
        ThrowUtils.throwIf(ObjUtil.isEmpty(id), ErrorCode.PARAMS_ERROR);
        //取出Token
        String token = request.getHeader("Auth");
        //校验Token
        ThrowUtils.throwIf(!jwtUtils.checkToken(token), ErrorCode.NOT_LOGIN_ERROR);
        //判断redis是否存在token
        ThrowUtils.throwIf(!redisUtils.hasKey(TOKEN_PRE + token), ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(!redisUtils.hasKey(USER_ID + id), ErrorCode.NOT_LOGIN_ERROR);
        //删除redis的token
        ThrowUtils.throwIf(!redisUtils.delete(TOKEN_PRE + token), ErrorCode.OPERATION_ERROR);
        ThrowUtils.throwIf(!redisUtils.delete(USER_ID + id), ErrorCode.OPERATION_ERROR);
    }

    @Override
    public void banUser(DeleteRequest deleteRequest, HttpServletRequest request) {
        //取出用户id
        Long id = deleteRequest.getId();
        //修改用户状态
        User user = new User();
        user.setId(id);
        user.setStatus(0);
        ThrowUtils.throwIf(!this.updateById(user), ErrorCode.OPERATION_ERROR);
        //删除redis用户信息
        if (redisUtils.hasKey(USER_ID + id)) {
            String userTokenKey = redisUtils.getString(USER_ID + id);
            redisUtils.delete(userTokenKey);
            redisUtils.delete(USER_ID + id);
        }
    }

    @Override
    public void unBanUser(DeleteRequest deleteRequest, HttpServletRequest request) {
        //取出用户id
        Long id = deleteRequest.getId();
        //修改用户状态
        User user = new User();
        user.setId(id);
        user.setStatus(1);
        ThrowUtils.throwIf(!this.updateById(user), ErrorCode.OPERATION_ERROR);
    }

    @Override
    public UserVO updateUserInfo(UpdateUserDTO updateUserDTO, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(updateUserDTO == null, ErrorCode.PARAMS_ERROR);
        Long userId = updateUserDTO.getId();
        ThrowUtils.throwIf(userId == null || userId <= 0, ErrorCode.PARAMS_ERROR, "用户ID不合法");
        
        // 校验权限：只能修改自己的信息，除非是管理员
        // 获取当前登录用户信息
        UserVO loginUser = getLoginUserInfo(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        
        // 普通用户只能修改自己的信息
        boolean isAdmin = loginUser.getRole() == 1;
        if (!isAdmin && !loginUser.getId().equals(userId)) {
            throw new RuntimeException(ErrorCode.NO_AUTH_ERROR.getMessage());
        }
        
        // 校验邮箱格式
        String email = updateUserDTO.getEmail();
        if (!StrUtil.isEmpty(email)) {
            ThrowUtils.throwIf(!Validator.isEmail(email), ErrorCode.PARAMS_ERROR, "邮箱格式不正确");
        }
        
        // 校验手机号格式
        String phone = updateUserDTO.getPhone();
        if (!StrUtil.isEmpty(phone)) {
            ThrowUtils.throwIf(!Validator.isMobile(phone), ErrorCode.PARAMS_ERROR, "手机号格式不正确");
        }
        
        // 校验用户是否存在
        User user = this.getById(userId);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        
        // 若修改用户名，需判断用户名是否已存在
        String username = updateUserDTO.getUsername();
        if (!StrUtil.isEmpty(username) && !username.equals(user.getUsername())) {
            QueryWrapper<User> userNameQuery = new QueryWrapper<>();
            userNameQuery.eq("username", username);
            ThrowUtils.throwIf(this.exists(userNameQuery), ErrorCode.PARAMS_ERROR, "用户名已存在");
        }
        
        // 更新用户信息
        BeanUtils.copyProperties(updateUserDTO, user);
        boolean result = this.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");
        
        // 更新Redis缓存中的用户信息
        // 获取用户token
        String tokenKey = redisUtils.getString(USER_ID + userId);
        if (!StrUtil.isEmpty(tokenKey)) {
            // 更新Redis中的用户信息
            redisUtils.set(tokenKey, JSON.toJSONString(user), redisExpire);
        }
        
        // 返回更新后的用户信息
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public UserPageVO listUsersByPage(UserQueryRequest userQueryRequest) {
        // 参数校验
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        
        // 构建查询条件
        QueryWrapper<User> queryWrapper = buildUserQueryWrapper(userQueryRequest);
        
        // 分页查询
        int current = userQueryRequest.getCurrent();
        int pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = this.page(new Page<>(current, pageSize), queryWrapper);
        
        // 转换为VO对象
        UserPageVO userPageVO = new UserPageVO();
        userPageVO.setCurrent(userPage.getCurrent());
        userPageVO.setPageSize(userPage.getSize());
        userPageVO.setTotal(userPage.getTotal());
        
        // 转换记录为VO
        List<UserVO> userVOList = new ArrayList<>();
        for (User user : userPage.getRecords()) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            userVOList.add(userVO);
        }
        userPageVO.setRecords(userVOList);
        
        return userPageVO;
    }
    
    @Override
    public UserVO addUser(UserManageDTO userManageDTO, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(userManageDTO == null, ErrorCode.PARAMS_ERROR);
        
        // 校验登录用户是否为管理员
        UserVO loginUser = getLoginUserInfo(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(!Role.Admin.equals(Role.getRoleByValue(loginUser.getRole())), ErrorCode.NO_AUTH_ERROR);
        
        // 校验必填参数
        String username = userManageDTO.getUsername();
        String password = userManageDTO.getPassword();
        String email = userManageDTO.getEmail();
        ThrowUtils.throwIf(StrUtil.hasBlank(username, password, email), ErrorCode.PARAMS_ERROR, "用户名、密码和邮箱为必填项");
        
        // 校验邮箱格式
        ThrowUtils.throwIf(!Validator.isEmail(email), ErrorCode.PARAMS_ERROR, "邮箱格式不正确");
        
        // 校验手机号格式
        String phone = userManageDTO.getPhone();
        if (!StrUtil.isEmpty(phone)) {
            ThrowUtils.throwIf(!Validator.isMobile(phone), ErrorCode.PARAMS_ERROR, "手机号格式不正确");
        }
        
        // 校验用户名是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        ThrowUtils.throwIf(this.exists(queryWrapper), ErrorCode.PARAMS_ERROR, "用户名已存在");
        
        // 密码加密
        String encryptPassword = MD5.create().digestHex(password, salt);
        
        // 创建用户
        User user = new User();
        BeanUtils.copyProperties(userManageDTO, user);
        user.setPassword(encryptPassword);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setIsDelete(0);
        
        // 如果没有指定角色和状态，设置默认值
        if (user.getRole() == null) {
            user.setRole(Role.User.getValue());
        }
        if (user.getStatus() == null) {
            user.setStatus(UserStatus.NORMAL.getStatus());
        }
        
        // 保存用户
        boolean saveResult = this.save(user);
        ThrowUtils.throwIf(!saveResult, ErrorCode.OPERATION_ERROR, "添加用户失败");
        
        // 返回添加的用户信息
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }
    
    @Override
    public UserVO updateUser(UserManageDTO userManageDTO, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(userManageDTO == null, ErrorCode.PARAMS_ERROR);
        Long userId = userManageDTO.getId();
        ThrowUtils.throwIf(userId == null || userId <= 0, ErrorCode.PARAMS_ERROR, "用户ID不合法");
        
        // 校验登录用户是否为管理员
        UserVO loginUser = getLoginUserInfo(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(!Role.Admin.equals(Role.getRoleByValue(loginUser.getRole())), ErrorCode.NO_AUTH_ERROR);
        
        // 校验用户是否存在
        User oldUser = this.getById(userId);
        ThrowUtils.throwIf(oldUser == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        
        // 校验邮箱格式
        String email = userManageDTO.getEmail();
        if (!StrUtil.isEmpty(email)) {
            ThrowUtils.throwIf(!Validator.isEmail(email), ErrorCode.PARAMS_ERROR, "邮箱格式不正确");
        }
        
        // 校验手机号格式
        String phone = userManageDTO.getPhone();
        if (!StrUtil.isEmpty(phone)) {
            ThrowUtils.throwIf(!Validator.isMobile(phone), ErrorCode.PARAMS_ERROR, "手机号格式不正确");
        }
        
        // 若修改用户名，需判断用户名是否已存在
        String username = userManageDTO.getUsername();
        if (!StrUtil.isEmpty(username) && !username.equals(oldUser.getUsername())) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            ThrowUtils.throwIf(this.exists(queryWrapper), ErrorCode.PARAMS_ERROR, "用户名已存在");
        }
        
        // 更新用户信息
        User user = new User();
        BeanUtils.copyProperties(userManageDTO, user);
        
        // 如果有密码，需要加密
        String password = userManageDTO.getPassword();
        if (!StrUtil.isEmpty(password)) {
            String encryptPassword = MD5.create().digestHex(password, salt);
            user.setPassword(encryptPassword);
        }
        
        user.setUpdateTime(new Date());
        boolean updateResult = this.updateById(user);
        ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR, "更新用户失败");
        
        // 如果用户被禁用，清除其登录状态
        if (user.getStatus() != null && user.getStatus().equals(UserStatus.BAN.getStatus())) {
            if (redisUtils.hasKey(USER_ID + userId)) {
                String userTokenKey = redisUtils.getString(USER_ID + userId);
                redisUtils.delete(userTokenKey);
                redisUtils.delete(USER_ID + userId);
            }
        }

        // 返回更新后的用户信息 
        User updatedUser = this.getById(userId);
        UserVO userVO = new UserVO();
        String tokenKey = redisUtils.getString(USER_ID + userId);
        BeanUtils.copyProperties(updatedUser, userVO);
        if (!StrUtil.isEmpty(tokenKey)) {
            // 更新Redis中的用户信息
            redisUtils.set(tokenKey, JSON.toJSONString(userVO), redisExpire);
        }
        return userVO;
    }
    
    @Override
    public Boolean deleteUser(DeleteRequest deleteRequest, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_ERROR);
        Long userId = deleteRequest.getId();
        ThrowUtils.throwIf(userId == null || userId <= 0, ErrorCode.PARAMS_ERROR, "用户ID不合法");
        
        // 校验登录用户是否为管理员
        UserVO loginUser = getLoginUserInfo(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(!Role.Admin.equals(Role.getRoleByValue(loginUser.getRole())), ErrorCode.NO_AUTH_ERROR);
        
        // 校验用户是否存在
        User user = this.getById(userId);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        
        // 不允许删除管理员账号
        ThrowUtils.throwIf(Role.Admin.equals(Role.getRoleByValue(user.getRole())), ErrorCode.OPERATION_ERROR, "不允许删除管理员账号");
        
        // 删除用户
        boolean result = this.removeById(userId);
        
        // 如果用户被删除，清除其登录状态
        if (result) {
            if (redisUtils.hasKey(USER_ID + userId)) {
                String userTokenKey = redisUtils.getString(USER_ID + userId);
                redisUtils.delete(userTokenKey);
                redisUtils.delete(USER_ID + userId);
            }
        }
        
        return result;
    }
    
    @Override
    public Boolean resetPassword(ResetPasswordDTO resetPasswordDTO, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(resetPasswordDTO == null, ErrorCode.PARAMS_ERROR);
        Long userId = resetPasswordDTO.getUserId();
        String newPassword = resetPasswordDTO.getNewPassword();
        ThrowUtils.throwIf(userId == null || userId <= 0, ErrorCode.PARAMS_ERROR, "用户ID不合法");
        ThrowUtils.throwIf(StrUtil.isEmpty(newPassword), ErrorCode.PARAMS_ERROR, "新密码不能为空");
        
        // 校验登录用户是否为管理员
        UserVO loginUser = getLoginUserInfo(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(!Role.Admin.equals(Role.getRoleByValue(loginUser.getRole())), ErrorCode.NO_AUTH_ERROR);
        
        // 校验用户是否存在
        User user = this.getById(userId);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        
        // 密码加密
        String encryptPassword = MD5.create().digestHex(newPassword, salt);
        
        // 更新密码
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setPassword(encryptPassword);
        updateUser.setUpdateTime(new Date());
        boolean result = this.updateById(updateUser);
        
        // 密码重置后，清除用户登录状态
        if (result) {
            if (redisUtils.hasKey(USER_ID + userId)) {
                String userTokenKey = redisUtils.getString(USER_ID + userId);
                redisUtils.delete(userTokenKey);
                redisUtils.delete(USER_ID + userId);
            }
        }
        
        return result;
    }
    
    @Override
    public Boolean changePassword(ChangePasswordDTO changePasswordDTO, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(changePasswordDTO == null, ErrorCode.PARAMS_ERROR);
        String oldPassword = changePasswordDTO.getOldPassword();
        String newPassword = changePasswordDTO.getNewPassword();
        ThrowUtils.throwIf(StrUtil.hasBlank(oldPassword, newPassword), ErrorCode.PARAMS_ERROR, "密码不能为空");
        
        // 获取当前登录用户
        UserVO loginUser = getLoginUserInfo(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        Long userId = loginUser.getId();
        
        // 校验用户是否存在
        User user = this.getById(userId);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        
        // 校验原密码是否正确
        String encryptOldPassword = MD5.create().digestHex(oldPassword, salt);
        ThrowUtils.throwIf(!encryptOldPassword.equals(user.getPassword()), ErrorCode.PARAMS_ERROR, "原密码不正确");
        
        // 校验新密码是否与原密码相同
        ThrowUtils.throwIf(oldPassword.equals(newPassword), ErrorCode.PARAMS_ERROR, "新密码不能与原密码相同");
        
        // 加密新密码
        String encryptNewPassword = MD5.create().digestHex(newPassword, salt);
        
        // 更新密码
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setPassword(encryptNewPassword);
        updateUser.setUpdateTime(new Date());
        boolean result = this.updateById(updateUser);
        
        // 密码修改成功后，清除用户登录状态，强制重新登录
        if (result) {
            if (redisUtils.hasKey(USER_ID + userId)) {
                String userTokenKey = redisUtils.getString(USER_ID + userId);
                redisUtils.delete(userTokenKey);
                redisUtils.delete(USER_ID + userId);
            }
        }
        
        return result;
    }
    
    /**
     * 构建用户查询条件
     *
     * @param userQueryRequest 查询请求
     * @return 查询条件包装器
     */
    private QueryWrapper<User> buildUserQueryWrapper(UserQueryRequest userQueryRequest) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        
        // 只查询未删除的用户
        queryWrapper.eq("is_delete", 0);
        
        // 根据条件查询
        Long id = userQueryRequest.getId();
        if (id != null) {
            queryWrapper.eq("id", id);
        }
        
        String username = userQueryRequest.getUsername();
        if (!StrUtil.isEmpty(username)) {
            queryWrapper.like("username", username);
        }
        
        String email = userQueryRequest.getEmail();
        if (!StrUtil.isEmpty(email)) {
            queryWrapper.like("email", email);
        }
        
        String phone = userQueryRequest.getPhone();
        if (!StrUtil.isEmpty(phone)) {
            queryWrapper.like("phone", phone);
        }
        
        Integer role = userQueryRequest.getRole();
        if (role != null) {
            queryWrapper.eq("role", role);
        }
        
        Integer status = userQueryRequest.getStatus();
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        Date createTimeStart = userQueryRequest.getCreateTimeStart();
        if (createTimeStart != null) {
            queryWrapper.ge("create_time", createTimeStart);
        }
        
        Date createTimeEnd = userQueryRequest.getCreateTimeEnd();
        if (createTimeEnd != null) {
            queryWrapper.le("create_time", createTimeEnd);
        }
        
        // 排序
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        if (!StrUtil.isEmpty(sortField)) {
            if ("ascend".equals(sortOrder)) {
                queryWrapper.orderByAsc(sortField);
            } else {
                queryWrapper.orderByDesc(sortField);
            }
        } else {
            // 默认按创建时间降序
            queryWrapper.orderByDesc("create_time");
        }
        
        return queryWrapper;
    }
}




